import { defineStore } from "pinia";
import { ref } from "vue";
import { HMI_DEVINFO_API, type DeviceInfoResponse } from "@/api/hmi/devinfo.api";

export const useDeviceInfoStore = defineStore("deviceInfo", () => {
  // 状态
  const deviceInfo = ref<DeviceInfoResponse | null>(null);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 获取设备信息
  const fetchDeviceInfo = async () => {
    loading.value = true;
    error.value = null;

    try {
      const response = await HMI_DEVINFO_API.getDeviceInfo();
      deviceInfo.value = response;
    } catch (err) {
      error.value = err instanceof Error ? err.message : "获取设备信息失败";
      console.error("获取设备信息失败:", err);
    } finally {
      loading.value = false;
    }
  };

  // 获取软件信息
  const getSoftwareInfo = () => {
    return deviceInfo.value?.[0] || [];
  };

  // 获取CPU信息
  const getCpuInfo = () => {
    return deviceInfo.value?.[1] || [];
  };

  // 获取虚端子信息
  const getVirtualTerminalInfo = () => {
    return deviceInfo.value?.[2] || [];
  };

  // 获取装置详细信息
  const getDeviceDetailInfo = () => {
    return deviceInfo.value?.[3] || [];
  };

  // 获取装置基本信息
  const getDeviceBasicInfo = () => {
    return deviceInfo.value?.[4] || [];
  };

  // 获取管理单信息
  const getManagementInfo = () => {
    return deviceInfo.value?.[5] || [];
  };

  // 重置状态
  const resetState = () => {
    deviceInfo.value = null;
    loading.value = false;
    error.value = null;
  };

  return {
    // 状态
    deviceInfo,
    loading,
    error,

    // 方法
    fetchDeviceInfo,
    getSoftwareInfo,
    getCpuInfo,
    getVirtualTerminalInfo,
    getDeviceDetailInfo,
    getDeviceBasicInfo,
    getManagementInfo,
    resetState,
  };
});

// 导出hook
export const useDeviceInfoStoreHook = () => {
  return useDeviceInfoStore();
};
